﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace PnJ.Aliyun.OTS.Util
{
    public class AliyunHelper
    {
        public static string GetSignature(string accessKeySecret, string canonicalURI, string httpRequestMethod, WebHeaderCollection headers)
        {
            string canonicalHeaders = GetCanonicalHeaders(headers);
            string stringToSign = GetRequestStringToSign(canonicalURI, httpRequestMethod, canonicalHeaders);
            string signature = EncryptHelper.HMACSHA1(accessKeySecret, stringToSign);
            return signature;
        }
        public static string GetAuthorization(string accessKeyID, string accessKeySecret, string canonicalURI, WebHeaderCollection headers)
        {
            string canoicalHeaders = GetCanonicalHeaders(headers);
            string stringToSign = string.Format("{0}{1}", canoicalHeaders, canonicalURI);
            string authorization = string.Format("OTS {0}:{1}", accessKeyID, EncryptHelper.HMACSHA1(accessKeySecret, stringToSign));
            return authorization;
        }
        private static string GetCanonicalHeaders(WebHeaderCollection headers)
        {
            StringBuilder sb = new StringBuilder();
            var keysInOrder = headers.AllKeys.Where(key => key.StartsWith("x-ots-")).OrderBy(key => key).ToList();
            foreach (var key in keysInOrder)
            {
                sb.Append(key.ToLower());
                sb.Append(":");
                sb.Append(headers[key].Trim());
                sb.Append("\n");
            }
            return sb.ToString();
        }

      
        public static string GetRequestStringToSign(string canonicalURI, string HTTPRequestMethod, string canonicalHeaders)
        {
            return canonicalURI + '\n' + HTTPRequestMethod + "\n\n" + canonicalHeaders;
        }

       

    }
}
